package com.bawei.reflection_annotation.room;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.bawei.reflection_annotation.R;

import java.lang.reflect.Field;

public class RoomActivity extends AppCompatActivity {

    private static final String TAG = "ytx";
    StringBuilder mStringBuilder ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);
        createTable(Student.class);
        createTable(Goods.class);


    }

    public void createTable(Class clazz){
        mStringBuilder = new StringBuilder();
        //通过反射获得Student的注解信息，拼接成创建表的sql语句
        //获得类上的Table注解
        MyTable table = (MyTable) clazz.getAnnotation(MyTable.class);
        //获得Table注解参数：表名
        String tableName = table.tableName();
        Log.d(TAG, "表名："+tableName);
        //CREATE TABLE USER3(id INT(4),NAME TEXT(100),)
        mStringBuilder.append("CREATE TABLE "+tableName+"(");
        //获得所有的字段
        Field[] fields = clazz.getDeclaredFields();
        //遍历获得字段上的注解信息
        for (Field field : fields) {
            MyField myField = field.getAnnotation(MyField.class);
            MyIds myIds = field.getAnnotation(MyIds.class);//主键
            String fieldName = myField.fieldName();
            MyType type = myField.type();
            int length = myField.length();

            //CREATE TABLE USER3(id INT(4) primary key auto_increment,NAME TEXT(100),)
            mStringBuilder.append(fieldName+" ");
            if(type == MyType.INT){
                mStringBuilder.append("int(")
                        .append(length)
                        .append(") ");
            }else if(type == MyType.TEXT){
                mStringBuilder.append("varchar(")
                        .append(length)
                        .append(") ");
            }
            //是否是主键
            if(myIds != null){
                mStringBuilder.append("primary key ");
                boolean auto = myIds.auto();
                if(auto){
                    mStringBuilder.append("auto_increment");
                }
            }
            mStringBuilder.append(",");
//            Log.d(TAG, "字段："+fieldName+":"+type+":"+length);

        }
        mStringBuilder.deleteCharAt(mStringBuilder.length()-1)
                .append(")");
        Log.d(TAG, "创建表的sql语句: "+mStringBuilder.toString());

    }
}